package library.and.xps.com.step.stepmodule;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.hardware.Sensor;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.os.Messenger;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.os.RemoteException;
import android.util.Log;

import java.util.Calendar;

import library.and.xps.com.step.PedoConstant;

public class StepService extends Service implements Handler.Callback {
    private final String TAG = "StepService";
    private SensorManager sensorManager;
    private StepDcretor stepDetector;
    private Messenger messenger;
    private WakeLock mWakeLock;
    private Handler mHandler;

    @Override
    public void onCreate() {
        super.onCreate();
        new Thread(new Runnable() {
            public void run() {
                startStepDetector();
            }
        }).start();

        mHandler = new Handler(Looper.getMainLooper(), this);
        messenger = new Messenger(mHandler);
    }

    @Override
    public void onStart(Intent intent, int startId) {
        super.onStart(intent, startId);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return super.onStartCommand(intent, Service.START_REDELIVER_INTENT, startId);
    }

    @Override
    public IBinder onBind(Intent intent) {
        return messenger.getBinder();
    }

    private void startStepDetector() {
//        if (sensorManager != null && stepDetector != null) {
//            sensorManager.unregisterListener(stepDetector);
//            sensorManager = null;
//            stepDetector = null;
//        }
//        sensorManager = (SensorManager) this
//                .getSystemService(SENSOR_SERVICE);
        getLock(this);

        // addBasePedoListener();
    }

    private void addBasePedoListener() {
        stepDetector = new StepDcretor(this);
        // 获得传感器的类型，这里获得的类型是加速度传感器
        // 此方法用来注册，只有注册过才会生效，参数：SensorEventListener的实例，Sensor的实例，更新速率
        Sensor sensor = sensorManager
                .getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        sensorManager.registerListener(stepDetector, sensor,
                SensorManager.SENSOR_DELAY_UI);
        stepDetector
                .setOnSensorChangeListener(new StepDcretor.OnSensorChangeListener() {

                    @Override
                    public void onChange() {

                    }
                });

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        stopSelf();
    }

    @Override
    public boolean onUnbind(Intent intent) {
        stopSelf();
        return super.onUnbind(intent);
    }

    synchronized private WakeLock getLock(Context context) {
        if (mWakeLock != null) {
            if (mWakeLock.isHeld())
                mWakeLock.release();
            mWakeLock = null;
        }

        PowerManager mgr = (PowerManager) context
                .getSystemService(Context.POWER_SERVICE);
        mWakeLock = mgr.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
                StepService.class.getName());
        mWakeLock.setReferenceCounted(true);
        Calendar c = Calendar.getInstance();
        c.setTimeInMillis(System.currentTimeMillis());
        int hour = c.get(Calendar.HOUR_OF_DAY);
        if (hour >= 23 || hour <= 6) {
            mWakeLock.acquire(5000);
        } else {
            mWakeLock.acquire(300000);
        }
        return (mWakeLock);
    }

    @Override
    public boolean handleMessage(Message msg) {
        switch (msg.what) {
            case PedoConstant.MSG_FROM_CLIENT:

                try {
                    Messenger messenger = msg.replyTo;
                    Message replyMsg = Message.obtain(null, PedoConstant.MSG_FROM_SERVER);
                    Bundle bundle = new Bundle();
                    bundle.putInt("step", StepDcretor.CURRENT_SETP);
                    replyMsg.setData(bundle);
                    messenger.send(replyMsg);

                } catch (RemoteException e) {
                    e.printStackTrace();
                }

                break;
            case PedoConstant.MSG_FROM_CLIENT_UNBIND_SERVICE:
                Log.e("StepService", "MSG_FROM_CLIENT_UNBIND_SERVICE");

                if (sensorManager != null && stepDetector != null) {
                    sensorManager.unregisterListener(stepDetector);
                    sensorManager = null;
                    stepDetector = null;
                }

                break;
            case PedoConstant.MSG_FROM_CLIENT_BIND_SERVICE:
                Log.e("StepService", "MSG_FROM_CLIENT_BIND_SERVICE");
                sensorManager = (SensorManager) this
                        .getSystemService(SENSOR_SERVICE);
                addBasePedoListener();
                break;
        }
        return false;
    }
}
